<template>
    <div class="rule">
        <van-dialog
            v-model="diaVisible"
            title="批次规则"
            show-cancel-button
            confirm-button-color="#548af1"
            :lazy-render="true"
            :before-close="beforClose"
            @cancel="closeDialog"
            @confirm="confirmRule"
        >
            <div class="modal-container">
                <el-form ref="addBatchForm" :model="addBatchForm" label-width="110px" :rules="rules" @submit.native.prevent>
                    <el-form-item label="批次规则" prop="type" >
                        <el-select
                            v-model="addBatchForm.type"
                            filterable
                            placeholder="请选择"
                            style="width:80%"
                            @change="changeRulesType"
                        >
                            <el-option
                            v-for="item in numRuleTypesOptions"
                            :key="item.id"
                            :label="setRuleLabel(item.prefixDetail)"
                            :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <template v-if="!isAllHand">
                        <!-- :rules="{ required: true, message: '该参数是必填项', trigger: ['blur', 'change']}" -->
                        <el-form-item
                            v-for="(item, index) in ruleFormItems"
                            :key="index"
                            :label="item.name"
                            :prop="`prefix-${index}`"
                            :rules="{ required: item.type === 1, message: '该参数是必填项', trigger: ['blur', 'change']}"
                        >
                            <!-- type 为 1 是人工输入-->
                            <el-input
                            v-model="addBatchForm[`prefix-${index}`]"
                            placeholder="请输入内容"
                            clearable
                            style="width: 60%"
                            :disabled="item.type !== 1"
                            />
                            <img v-if="item.type === 1" src="@/assets/images/scan02.png" class="scan-img" @click="scanChange(index)" />
                        </el-form-item>
                    </template>
                </el-form>
            </div>
        </van-dialog>
    </div>
</template>

<script>
import {
    getNumRuleDetailByType as numRuleTypes,
    getNumRuleSeqByType as numRuleDetail,
} from '@/api/inventory'
// import { v4 as uuidv4 } from 'uuid'
// import { newAddBarCode, getWorkerOrderCodeList, getNewAddBarCodeProgress } from '@/api/labelRule'

export default {
    props: {
        addBatchParams: {
            type: Object,
            default: () => ({})
        },
        addBatchVisible: {
            type: Boolean,
            default: false
        },
    },
    data() {
        var validateBatchCodeNum = (rule, value, callback) => {
            console.log(value, 'value')
            if (!value && value !== 0) {
                callback(new Error('该项为必填！'))
            } else {
                console.log(value, 'intValue')
                if (!(/^\+?[1-9]\d*$/.test(value))) {
                callback(new Error('请输入正整数'))
                } else {
                callback()
                }
            }
        }
        return {
            diaVisible: false,
            addBatchForm: { inputType: 'a', batchCodeNum: '', receiveMaterialNum: '', everyBatchNum: '', batchSpecs: '', type: '' },
            rules: { 
                    batchCodeNum: [{
                    required: true,
                    validator: validateBatchCodeNum,
                    trigger: ['blur', 'change']
                }],
                type:[
                    { required: true, message: '不能为空', trigger: 'blur' },
                ]
            },
            numRuleTypesOptions: [],
            ruleFormItems: [],
            percentage: null,
            isAllHand: false, // 是否是纯人工输入
        }
    },
    watch: {
        addBatchVisible: {
            immediate: true,
            deep: true,
            handler(newValue, oldValue) {
                console.log(this.addBatchParams, '====newValue')
                this.diaVisible = newValue
            }
        }
    },
    created () {
        this.getNumRuleTypes()
    },
    
    methods: {
        scanChange(index) {
            const that = this;
            if (process.env.NODE_ENV === "development") {
                this.addBatchForm[`prefix-${index}`] = "CK2023091900048";
            } else {
                window.flutter_inappwebview.callHandler("qrCode").then((res) => {
                if (res) {
                    this.addBatchForm[`prefix-${index}`] = res;
                }
                });
            }
        },
        beforClose(action, done){
            if (action == "confirm") {
                this.$refs.addBatchForm.validate((valid) => {
                if (valid) {
                    done();
                } else {
                    done(false);
                }
                });
            } else {
                done();
            }
        },
        changeInputType() {
            this.addBatchForm.batchCodeNum = ''
            this.addBatchForm.receiveMaterialNum = ''
            this.addBatchForm.everyBatchNum = ''
            this.addBatchForm.type = ''
            this.ruleFormItems = []
            for (var key in this.addBatchForm) {
                if (key.startsWith('prefix-')) {
                this.$delete(this.addBatchForm, key)
                }
            }
        },
        // 获取编码规则类型
        async getNumRuleTypes () {
            const {
                data: { code, data, message }
            } = await numRuleTypes({ typeCode: 62 })
            if (code === '200') {
                this.numRuleTypesOptions = data || []
                const arr = this.numRuleTypesOptions.filter(i=>i.isDefault)
                if(arr.length>0){
                    this.addBatchForm.type = arr[arr.length -1].id
                    this.changeRulesType(arr[arr.length -1].id)
                }
                
                if (data.length === 0) {
                return this.$notify({
                    title: '提示',
                    message: `编码规则未配置，请先配置单据编码规则`,
                    type: 'warning',
                    duration: 2000
                })
                }
            } else {
                this.$notify({
                title: '提示',
                message: message || '服务异常',
                type: 'error',
                duration: 2000
                })
            }
        },
        // 关闭弹窗
        closeDialog() {
            console.log('9999')
            this.$emit('closeDialog')
        },
        // 格式化下拉展示内容
        setRuleLabel (prefixDetail) {
            const nPrefixDetail = JSON.parse(prefixDetail || '[]')
            const str = nPrefixDetail.reduce((str, i) => {
                str = str + i.name + '-'
                return str
            }, '')
            return str.slice(0, -1)
        },
        async changeRulesType (val) {
            // 重置表单中的规则
            for (var key in this.addBatchForm) {
                if (key.startsWith('prefix-')) {
                this.$delete(this.addBatchForm, key)
                }
            }
            const pNumberMap = {
                12: '',
                13: '',
                14: ''
            }
            const pRelatedMap = {
                supplier: '',
                purchase: '',
                purchaseReceipt: ''
            }
            const param = {
                id: val,
                workOrderNumber: '',
                materialCode: this.addBatchParams.productCode,
                type: 'otherInStockBatch',
                ruleType: 'otherInStockBatch',
                numberMap: pNumberMap,
                relatedMap: pRelatedMap
            }
            const { data: { code, data: { prefixValueList = [] }, message }} = await numRuleDetail(param)  
            if (code === '200') {
                this.ruleFormItems = prefixValueList
                prefixValueList.forEach((item, index) => {
                // this.addBatchForm
                this.$set(this.addBatchForm, `prefix-${index}`, item.value)
                })
                // 只有一条规则
                if (prefixValueList.length === 1) {
                if (prefixValueList[0].type === 1) { // 全人工输入
                    this.matualInputVisible = true
                    this.isAllHand = true
                } else {
                    this.isAllHand = false
                }
                // 含有多条规则
                } else {
                if (prefixValueList.every(i => i.type === 1)) {
                    this.matualInputVisible = true
                    this.isAllHand = true
                } else {
                    this.isAllHand = false
                }
                }
            } else {
                this.$notify({
                title: '提示',
                message: message || '服务异常',
                type: 'error',
                duration: 2000
                })
            }
        },
        // 确认
        confirmRule() {
            this.$refs['addBatchForm'].validate(async(valid) => {
                if (valid) {
                    // 批次规则生成
                    if (!this.isAllHand) {
                        this.$emit('confirmRule', this.addBatchForm, this.ruleFormItems)
                    }
                }
            })
        }
    }

}

</script>

<style lang="scss" scoped>
.modal-container{
    margin-top: 30px;
}
.scan-img{
    width: 20px;
    height: 20px;
    margin-left: 15px;
}
</style>
<style>
.el-select-dropdown{
    z-index: 20010 !important;
}
</style>

